package com.yidianyanglao.buyBack.service.impl;

import com.yidianyanglao.buyBack.bean.BankcardBean;
import com.yidianyanglao.buyBack.bean.BuybackNoticeBean;
import com.yidianyanglao.buyBack.bean.RepurchaseRecordBean;
import com.yidianyanglao.buyBack.mapper.BuyBackMapper;
import com.yidianyanglao.buyBack.service.BuyBackService;
import com.yidianyanglao.common.bean.Notice;
import com.yidianyanglao.common.bean.Series;
import com.yidianyanglao.common.mapper.CommonMapper;
import com.yidianyanglao.core.bean.RetBean;
import com.yidianyanglao.core.enums.Code;
import com.yidianyanglao.core.enums.NoticeType;
import com.yidianyanglao.core.exception.CustomException;
import com.yidianyanglao.core.util.DigestUitl;
import com.yidianyanglao.core.util.Log;
import com.yidianyanglao.user.bean.LuckyTreeBean;
import com.yidianyanglao.user.bean.RecommRecord;
import com.yidianyanglao.user.bean.SeedDetailsBean;
import com.yidianyanglao.user.bean.UserBean;
import com.yidianyanglao.user.mapper.UserMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2016/11/9.
 */
@Service
public class BuyBackServiceImpl implements BuyBackService {


    @Resource
    private UserMapper userMapper;

    @Resource
    private BuyBackMapper bbm;

    @Resource
    private CommonMapper cm;


    @Transactional
    @Override
    public void buyBackApply(String token, String applySeednum,BankcardBean bank,String seedType,BigDecimal seedNum,double num) {



        UserBean userBean = userMapper.getUserInfoByToken(token);
        if(userBean == null){
            Log.info("BuyBackServiceImpl--> (Transactional)buyBackApply-->,用户id:{},回购获取用户失败。",userBean.getId());
            throw new CustomException(Code.ERROR, "服务器繁忙");
        }

        //进行验证
        //判断历史和，失败的不算
        double bankSeedSum=bbm.getBankSeedSum(userBean.getId());
        if(bankSeedSum >50000){
            throw new CustomException(Code.ERROR, "超出今日兑换上线，请减少金额或者明天重试！");
        }else{
            //当前交易额是否大于50000
            //当前+历史的和
            BigDecimal big = seedNum.add(new BigDecimal(bankSeedSum));
            if(big.compareTo(BigDecimal.valueOf(50000.00))>=1){
                throw new CustomException(Code.ERROR, "超出今日兑换上线，请减少金额或者明天重试！");
            }
        }

        if(Integer.valueOf(applySeednum) % 100 != 0){
            throw new CustomException(Code.ERROR, "回购数量只能是整百！");
        }

        if(seedType.equals("1")){
            int r = seedNum.compareTo(BigDecimal.valueOf(100.00));
            if(r>-1){
                num = userBean.getOrdinarySeed() - seedNum.doubleValue();
                if(num<0){
                    throw new CustomException(Code.ERROR, "用户普通种子数量不足不可回购");
                }
            }else{
                throw new CustomException(Code.ERROR, "普通种子的回购数量不能小于100");
            }
        }else if(seedType.equals("2")){
            int r = seedNum.compareTo(BigDecimal.valueOf(100.00));
            if(r>-1){
                num = userBean.getRewardSeed() - seedNum.doubleValue();
                if(num<0){
                    throw new CustomException(Code.ERROR, "用户奖励种子数量不足不可回购");
                }
            }else{
                throw new CustomException(Code.ERROR, "奖励种子的回购数量不能小于100");
            }
        }

        //产生回购记录
        RepurchaseRecordBean repurchaseRecordBean = new RepurchaseRecordBean();
        repurchaseRecordBean.setRepurchaseId("MHG"+String.valueOf(System.currentTimeMillis()).toString().substring(0,11));
        repurchaseRecordBean.setUserId(userBean.getId());
        repurchaseRecordBean.setUserName(userBean.getRealname());
        repurchaseRecordBean.setCreatedate(new Date());
        repurchaseRecordBean.setBankId(bank.getId());
        repurchaseRecordBean.setBankName(bank.getBankName());
        repurchaseRecordBean.setCardNumber(bank.getCardnumber());
        repurchaseRecordBean.setApplySeednum(Double.valueOf(applySeednum));
        repurchaseRecordBean.setProcessFeeValue(5);
        repurchaseRecordBean.setAccountBalance((double) num);
        repurchaseRecordBean.setBranchName(bank.getBranchName());    //支行信息
        repurchaseRecordBean.setMobile(bank.getMobile());            //手机号码
        repurchaseRecordBean.setSeedType(Integer.valueOf(seedType));

        if(seedType.equals("2")){
            repurchaseRecordBean.setTaxpoint("4.8%");
            BigDecimal point = new BigDecimal(0.048);
            double pointValue = seedNum.multiply(point).doubleValue();
            repurchaseRecordBean.setTaxpointValue(pointValue);

            repurchaseRecordBean.setProcessFee("税点值:"+pointValue+",手续费:5");
            repurchaseRecordBean.setSeednum(Double.valueOf(applySeednum)-5-pointValue);
        }else{
            repurchaseRecordBean.setProcessFee("手续费:5");
            repurchaseRecordBean.setSeednum(Double.valueOf(applySeednum)-5);
        }
        //插入一条记录
        int isOK = bbm.addRepurchase(repurchaseRecordBean);
        //消息内容
        String content = "";
        //明细对象
        SeedDetailsBean sdb = new SeedDetailsBean();

        int seedResult = 0;
        //减种子，并根据种子明细生成消息和明细值
        if( isOK == 1){
            if(seedType.equals("1")){
                seedResult = bbm.reduceOrdinarySeed(num,userBean.getId(),userBean.getVersion());
                content = "申请普通种子回购，单号为：【"+repurchaseRecordBean.getRepurchaseId()+"】，申请金额为"+repurchaseRecordBean.getApplySeednum()+"。";
                sdb.setSeedtype("普通");
            }else if(seedType.equals("2")){
                seedResult = bbm.reduceRewardSeed(num,userBean.getId(),userBean.getVersion());
                content = "申请奖励种子回购，单号为：【"+repurchaseRecordBean.getRepurchaseId()+"】，申请金额为"+repurchaseRecordBean.getApplySeednum()+"。";
                sdb.setSeedtype("奖励");
                sdb.setTaxPointValue(repurchaseRecordBean.getTaxpointValue());
                sdb.setTaxPoint(0.048);
            }
            if(seedResult<=0){
                Log.info("BuyBackServiceImpl--> (Transactional)buyBackApply-->,用户id:{},更新用户种子时失败。",userBean.getId());
                throw new CustomException(Code.ERROR, "服务器繁忙");
            }
            //记录消息
            Notice notice = new Notice(repurchaseRecordBean.getUserId(),repurchaseRecordBean.getUserName(),content,NoticeType.BUYBACK.getNum(),0);
            cm.addNotice(notice);
            //明细赋值
            sdb.setUserId(Integer.parseInt(repurchaseRecordBean.getUserId()+""));
            sdb.setName("回购");
            sdb.setChangeSeed(-repurchaseRecordBean.getApplySeednum());
            sdb.setRemainingSeed(repurchaseRecordBean.getAccountBalance());
            sdb.setCreatedate(new Date());
            sdb.setProcessingFee(5);
            //执行插入明细
            isOK = userMapper.addSeedDetailZz(sdb);
            if(isOK == 0) {
                throw new CustomException(Code.ERROR, "系统繁忙，请稍后重试！");
            }
            //记录银行卡回购时间
            bank.setRepurdate(new Date());
            bbm.setBackRepurdate(bank);
        }else{
            throw new CustomException(Code.ERROR, "申请回购失败");
        }
    }
}
